<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/28/24
 * Time: 2:22 PM
 */

namespace App\Services;


use App\Models\WechatAccount;
use App\Models\WechatAccountCategory;
use App\Models\WechatCategory;
use App\Models\WechatUserAdmin;
use Carbon\Carbon;
use function League\Flysystem\toArray;

class CategoryService
{


    /**
     * 获取列表
     *
     * @param $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getList($params)
    {
        $pageSize = $params['page_size'] ?? 50;

        $list = WechatCategory::query()->paginate($pageSize);
        foreach ($list as &$item) {
            $item->user_count = WechatAccountCategory::query()->where('category_id', $item->id)->count();
        }

        return $list;
    }


    /**
     * 获取所有分类
     *
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getAll()
    {
        return WechatCategory::query()->select('id', 'category_name')->get();
    }


    /**
     * 更新分类
     *
     * @param $params
     * @return bool
     */
    public function save($params)
    {
        $id   = $params['id'] ?? 0;
        $name = $params['name'] ?? '';
        if (!$name) {

            return false;
        }

        if ($id) {
            $category                = WechatCategory::query()->find($id);
            $category->category_name = $name;

            return $category->save();
        } else {
            $category             = WechatCategory::query()->firstOrNew(['category_name' => $name]);
            $category->created_at = Carbon::now()->toDateTimeString();

            return $category->save();
        }

    }


    /**
     * 删除分类
     *
     * @param $id
     * @return bool|mixed|null
     */
    public function delete($id)
    {
        $category = WechatCategory::query()->find($id);

        return $category->delete();
    }


    /**
     * 获取分类号池
     *
     * @return array
     */
    public function getCategoryPool()
    {
        $ac     = WechatAccountCategory::query()
            ->with(['user.department', 'category'])
            ->select('corp_id', 'user_id', 'category_id')
            ->whereIn('user_id', UtilityService::getPermissionUserIds())
            ->get();
        $result = [];
        foreach ($ac as $item) {
            if (isset($result[$item->category_id])) {
                array_push($result[$item->category_id]['users'], $item->user->toArray());
            } else {
                $result[$item->category_id] = [
                    'category_id'   => $item->category_id,
                    'category_name' => optional($item->category)->category_name ?? '',
                    'users'         => [$item->user->toArray()]
                ];

            }
        }

        return array_values($result);
    }
}
